package com.sophie.chapter1;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringSerializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;

public class ConsumerFastStart {

    private static final String brokerList = "120.79.216.84:8196";

    private static final String topic = "heima";

    private static final String groupId = "group.demo";

    public static void main(String[] args) {
        Properties properties = new Properties();

        // 设置KEY反序列化器
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
//        properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        // 设置值反序列化器
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
//        properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        // 设置集群地址
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList);
//        properties.put("bootstrap.servers", brokerList);


        // 消费组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
//        properties.put("group.id", groupId);


        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);
        // 订阅主题
        consumer.subscribe(Collections.singletonList(topic));

        // 自动应答，指定分区
        consumer.assign(Arrays.asList(new TopicPartition(topic, 0)));

        while (true) {
            // 拉取消息
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
            for (ConsumerRecord<String, String> record : records) {
                System.out.println("\n\n");
                System.out.println("headers=" + record.headers() + ",offset=" + record.offset() + ",partition=" + record.partition() + ",topic=" + record.topic() + ",key=" + record.key() + ",value=" + record.value());
                System.out.println("\n\n");
            }
        }


    }
}
